<template>
	<view class="container">
		<!-- 状态栏 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 导航栏 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<image src="/static/icons/back.png" mode="aspectFit" class="back-icon"></image>
			</view>
			<view class="nav-title">拼图游戏</view>
		</view>
		
		<!-- 游戏信息 -->
		<view class="game-info">
			<view class="info-item">
				<text class="value">{{moves}}</text>
				<text class="label">步数</text>
			</view>
			<view class="info-item">
				<text class="value">{{formatTime(time)}}</text>
				<text class="label">用时</text>
			</view>
		</view>
		
		<!-- 拼图板 -->
		<view class="puzzle-board" :style="{ width: boardSize + 'px', height: boardSize + 'px' }">
			<view 
				v-for="(tile, index) in tiles" 
				:key="index"
				:class="['puzzle-tile', { 'empty': tile === 0 }]"
				:style="getTileStyle(index)"
				@click="moveTile(index)"
			>
				<text v-if="tile !== 0">{{tile}}</text>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-btns">
			<button class="action-btn" @click="startNewGame">重新开始</button>
			<button class="action-btn" @click="showHelp">游戏规则</button>
		</view>

		<!-- 完成弹窗 -->
		<uni-popup ref="completePopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">恭喜完成</view>
				<view class="game-stats">
					<view class="stats-item">
						<text class="label">用时</text>
						<text class="value">{{formatTime(time)}}</text>
					</view>
					<view class="stats-item">
						<text class="label">步数</text>
						<text class="value">{{moves}}步</text>
					</view>
				</view>
				<view class="reward-info">
					<text class="reward-text">获得奖励</text>
					<text class="reward-amount">{{calculateReward()}}金币</text>
				</view>
				<button class="confirm-btn" @click="closePopup">确定</button>
			</view>
		</uni-popup>
		
		<!-- 帮助弹窗 -->
		<uni-popup ref="helpPopup" type="center">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">游戏规则</text>
				</view>
				<view class="help-content">
					<text class="help-text">1. 点击数字方块可以移动它到相邻的空格</text>
					<text class="help-text">2. 将所有数字按顺序排列即可获胜</text>
					<text class="help-text">3. 步数越少奖励越多</text>
					<text class="help-text">4. 每天可以玩3次</text>
				</view>
				<button class="confirm-btn" @click="closeHelp">知道了</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			statusBarHeight: 0,
			boardSize: 300,
			tiles: [],
			moves: 0,
			time: 0,
			timer: null,
			isPlaying: false
		}
	},
	onLoad() {
		this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
		this.startNewGame();
	},
	onUnload() {
		this.stopTimer();
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},
		
		// 开始新游戏
		startNewGame() {
			this.tiles = this.generatePuzzle();
			this.moves = 0;
			this.time = 0;
			this.isPlaying = true;
			this.startTimer();
		},
		
		// 生成拼图
		generatePuzzle() {
			let tiles = Array.from({length: 16}, (_, i) => i);
			
			// 打乱拼图
			for (let i = tiles.length - 1; i > 0; i--) {
				const j = Math.floor(Math.random() * (i + 1));
				[tiles[i], tiles[j]] = [tiles[j], tiles[i]];
			}
			
			// 确保可解
			if (!this.isSolvable(tiles)) {
				if (tiles[0] !== 0 && tiles[1] !== 0) {
					[tiles[0], tiles[1]] = [tiles[1], tiles[0]];
				} else {
					[tiles[tiles.length - 2], tiles[tiles.length - 1]] = 
					[tiles[tiles.length - 1], tiles[tiles.length - 2]];
				}
			}
			
			return tiles;
		},
		
		// 检查是否可解
		isSolvable(tiles) {
			let inversions = 0;
			let blankRow = Math.floor(tiles.indexOf(0) / 4);
			
			for (let i = 0; i < tiles.length - 1; i++) {
				if (tiles[i] === 0) continue;
				for (let j = i + 1; j < tiles.length; j++) {
					if (tiles[j] === 0) continue;
					if (tiles[i] > tiles[j]) inversions++;
				}
			}
			
			if (blankRow % 2 === 0) {
				return inversions % 2 === 0;
			} else {
				return inversions % 2 === 1;
			}
		},
		
		// 获取方块样式
		getTileStyle(index) {
			const tile = this.tiles[index];
			if (tile === 0) return {};
			
			const size = (this.boardSize - 20) / 4;
			const row = Math.floor(index / 4);
			const col = index % 4;
			
			const hue = (tile * 20) % 360;
			const lightness = 85;
			
			return {
				width: size + 'px',
				height: size + 'px',
				top: (row * (size + 5)) + 'px',
				left: (col * (size + 5)) + 'px',
				backgroundColor: `hsl(${hue}, 70%, ${lightness}%)`
			};
		},
		
		// 移动方块
		moveTile(index) {
			if (!this.isPlaying) return;
			
			const emptyIndex = this.tiles.indexOf(0);
			const row = Math.floor(index / 4);
			const emptyRow = Math.floor(emptyIndex / 4);
			const col = index % 4;
			const emptyCol = emptyIndex % 4;
			
			if (
				(Math.abs(row - emptyRow) === 1 && col === emptyCol) ||
				(Math.abs(col - emptyCol) === 1 && row === emptyRow)
			) {
				[this.tiles[index], this.tiles[emptyIndex]] = [this.tiles[emptyIndex], this.tiles[index]];
				this.moves++;
				
				if (this.checkWin()) {
					this.gameComplete();
				}
			}
		},
		
		// 检查是否胜利
		checkWin() {
			return this.tiles.every((tile, index) => {
				if (index === this.tiles.length - 1) {
					return tile === 0;
				}
				return tile === index + 1;
			});
		},
		
		// 游戏完成
		gameComplete() {
			this.isPlaying = false;
			this.stopTimer();
			this.$refs.completePopup.open();
		},
		
		// 开始计时
		startTimer() {
			this.stopTimer();
			this.timer = setInterval(() => {
				this.time++;
			}, 1000);
		},
		
		// 停止计时
		stopTimer() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		
		// 计算奖励
		calculateReward() {
			// 基础奖励10金币
			let reward = 10;
			
			// 根据步数和时间计算额外奖励
			if (this.moves < 100) {
				reward += Math.floor((100 - this.moves) / 10);
			}
			
			if (this.time < 180) {
				reward += Math.floor((180 - this.time) / 30);
			}
			
			return reward;
		},
		
		// 格式化时间
		formatTime(seconds) {
			const minutes = Math.floor(seconds / 60);
			seconds = seconds % 60;
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},
		
		// 显示帮助
		showHelp() {
			this.$refs.helpPopup.open();
		},
		
		// 关闭帮助
		closeHelp() {
			this.$refs.helpPopup.close();
		},
		
		// 关闭完成弹窗
		closePopup() {
			this.$refs.completePopup.close();
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f8f9fa;
}

.status-bar {
	background: #FF6B6B;
}

.nav-bar {
	display: flex;
	align-items: center;
	height: 44px;
	background: #FF6B6B;
	padding: 0 15px;
}

.nav-left {
	width: 40px;
	height: 100%;
	display: flex;
	align-items: center;
}

.back-icon {
	width: 20px;
	height: 20px;
	filter: brightness(0) invert(1);
}

.nav-title {
	flex: 1;
	text-align: center;
	font-size: 16px;
	font-weight: 500;
	color: #ffffff;
}

.game-info {
	display: flex;
	justify-content: center;
	gap: 40px;
	margin: 20px 0;
	
	.info-item {
		text-align: center;
		
		.value {
			font-size: 32px;
			font-weight: bold;
			color: #FF6B6B;
			display: block;
		}
		
		.label {
			font-size: 14px;
			color: #666666;
			margin-top: 4px;
		}
	}
}

.puzzle-board {
	position: relative;
	margin: 0 auto;
	background-color: #ffffff;
	border-radius: 16px;
	padding: 10px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.puzzle-tile {
	position: absolute;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 8px;
	font-size: 24px;
	font-weight: bold;
	color: #ffffff;
	transition: all 0.2s ease;
	box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	
	&.empty {
		background-color: transparent !important;
		box-shadow: none;
	}
}

.action-btns {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 30px;
	display: flex;
	gap: 15px;
	padding: 0 20px;
	
	.action-btn {
		flex: 1;
		height: 44px;
		line-height: 44px;
		background: #FF6B6B;
		color: #ffffff;
		border-radius: 22px;
		font-size: 16px;
		
		&:active {
			opacity: 0.9;
		}
	}
}

.popup-content {
	width: 280px;
	background-color: #ffffff;
	border-radius: 16px;
	padding: 30px 20px;
	text-align: center;
}

.popup-title {
	font-size: 24px;
	font-weight: bold;
	color: #333333;
	margin-bottom: 30px;
}

.game-stats {
	display: flex;
	justify-content: space-around;
	margin-bottom: 20px;
	
	.stats-item {
		text-align: center;
		
		.label {
			font-size: 14px;
			color: #666666;
			margin-bottom: 5px;
		}
		
		.value {
			font-size: 20px;
			font-weight: 500;
			color: #333333;
		}
	}
}

.reward-info {
	margin-bottom: 30px;
	
	.reward-text {
		font-size: 14px;
		color: #666666;
		margin-bottom: 10px;
	}
	
	.reward-amount {
		font-size: 32px;
		font-weight: bold;
		color: #FF6B6B;
	}
}

.confirm-btn {
	width: 100%;
	height: 44px;
	line-height: 44px;
	background: #FF6B6B;
	color: #ffffff;
	border-radius: 22px;
	font-size: 16px;
	
	&:active {
		opacity: 0.9;
	}
}

.help-content {
	margin-bottom: 30px;
	text-align: left;
	
	.help-text {
		font-size: 14px;
		color: #666666;
		line-height: 1.8;
		display: block;
	}
}
</style> 